package com.hudongwx.my_shian.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.hudongwx.my_shian.R;
import com.hudongwx.my_shian.adapter.homeAdapter.MyChosenAdapter;
import com.hudongwx.my_shian.adapter.homeAdapter.MyClassifyAdapter;
import com.hudongwx.my_shian.adapter.homeAdapter.MyHotAdapter;
import com.hudongwx.my_shian.adapter.homeAdapter.MyImgPlayAdapter;
import com.hudongwx.my_shian.utils.API;
import com.hudongwx.my_shian.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 主页
 */

public class HomePageFragment extends Fragment {
    MyHomeAdapter adapter;
    private JSONArray play;
    private JSONArray classify;
    private JSONArray hot;
    private JSONArray chosen;
    private ListView listView;
    private ImageHandler handler;
    private ViewPager viewPager;
    private List<ImageView> dataImg;
    View view;
    private String TAG = "HomePageFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_home_page, container, false);
            listView = (ListView) view.findViewById(R.id.home_list);
            handler = new ImageHandler(new WeakReference(HomePageFragment.this));

//            dataImg = new ArrayList<>();
////            for (int i=0;i<3;i++){
//            ImageView iv1 = new ImageView(getActivity());
//            ImageView iv2 = new ImageView(getActivity());
//
//            ImageView iv3 = new ImageView(getActivity());
//
//            iv1.setImageResource(R.drawable.car_t);
//            iv2.setImageResource(R.drawable.community_t);
//            iv3.setImageResource(R.drawable.my_t);
//            dataImg.add(iv1);
//            dataImg.add(iv2);
//            dataImg.add(iv3);
////            }

            //适配器
            adapter = new MyHomeAdapter(play, classify, hot, chosen);
            //绑定适配器到listView
            listView.setAdapter(adapter);
            play();
            classify();
            hot();
            chosen();
        }
        return view;
    }


    public void play() {
        RequestParams params = new RequestParams(API.getViewPagerImg());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                //请求成功
                try {
                    JSONArray data = result.getJSONArray("Data");
                    dataImg = new ArrayList<>();
                    for (int i = 0; i < data.length(); i++) {
                        ImageView imageView = new ImageView(getActivity());
                        x.image().bind(imageView, data.getJSONObject(i).getString("Url"));
                        dataImg.add(imageView);
                    }
                    Log.i("info", "onSuccessaaa: -----------------------" + dataImg.size());

                    adapter.updatePlay(data, dataImg);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //请求错误
                Log.i("info", "onError: ");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //请求失败
                Log.i("info", "onCancelled: ");
            }

            @Override
            public void onFinished() {
                //请求完
                Log.i("info", "onFinished: ");
            }
        });
    }

    public void classify() {
        RequestParams params = new RequestParams(API.getFoodMenu());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                //请求成功
                try {
                    JSONArray data = result.getJSONArray("Data");
                    adapter.updateClassify(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //请求错误
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //请求失败
            }

            @Override
            public void onFinished() {
                //请求完
            }
        });
    }

    public void hot() {
        RequestParams params = new RequestParams(API.getCommunity());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                //请求成功
                try {
                    JSONArray data = result.getJSONArray("Data");
                    adapter.updateHot(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //请求错误
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //请求失败
            }

            @Override
            public void onFinished() {
                //请求完
            }
        });
    }

    public void chosen() {
        RequestParams params = new RequestParams(API.getSpecial());
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                //请求成功
                try {
                    JSONArray data = result.getJSONArray("Data");
                    adapter.updateChosen(data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //请求错误
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //请求失败
            }

            @Override
            public void onFinished() {
                //请求完
            }
        });
    }

    //适配器
    class MyHomeAdapter extends BaseAdapter {

        private List<ImageView> data;
        private JSONArray play;
        private JSONArray classify;
        private JSONArray hot;
        private JSONArray chosen;

        public MyHomeAdapter(JSONArray play, JSONArray classify, JSONArray hot, JSONArray chosen) {
            this.play = play;
            this.classify = classify;
            this.hot = hot;
            this.chosen = chosen;
        }

        public void updatePlay(JSONArray play, List<ImageView> data) {
            this.data = data;
            this.play = play;
            notifyDataSetChanged();
        }

        public void updateClassify(JSONArray classify) {
            this.classify = classify;
            notifyDataSetChanged();
        }

        public void updateHot(JSONArray hot) {
            this.hot = hot;
            notifyDataSetChanged();
        }

        public void updateChosen(JSONArray chosen) {
            this.chosen = chosen;
            notifyDataSetChanged();
        }


        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public Object getItem(int position) {
            return 0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.i(TAG, "getView:======================== " + position);
            switch (position) {
                case 0:
                    //解析布局
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.home_img_play, null);
                    //获取控件
                    ImageView imageView = (ImageView) convertView.findViewById(R.id.home_img_play_iv);
                    viewPager = (ViewPager) convertView.findViewById(R.id.home_img_play_vp);
                    MyImgPlayAdapter adapter0 = null;
                    if (null != data) {
                        viewPager.setVisibility(View.VISIBLE);
                        imageView.setVisibility(View.GONE);
                        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                            //配合Adapter的currentItem字段进行设置。
                            @Override
                            public void onPageSelected(int arg0) {
                                Log.i(TAG, "onPageSelected: arg0=" + arg0);
                                handler.sendMessage(Message.obtain(handler, ImageHandler.MSG_PAGE_CHANGED, arg0, 0));
                            }

                            @Override
                            public void onPageScrolled(int arg0, float arg1, int arg2) {
                            }

                            //覆写该方法实现轮播效果的暂停和恢复
                            @Override
                            public void onPageScrollStateChanged(int arg0) {
                                Log.i(TAG, "onPageScrollStateChanged: 1=" + arg0);
                                switch (arg0) {

                                    case ViewPager.SCROLL_STATE_DRAGGING:
                                        handler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);
                                        break;
                                    case ViewPager.SCROLL_STATE_IDLE:
                                        Log.i(TAG, "onPageScrollStateChanged: 2=" + arg0);
                                        handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                        //适配器
                        adapter0 = new MyImgPlayAdapter(getActivity(), data);
                        //添加数据
                        viewPager.setAdapter(adapter0);


                        viewPager.setCurrentItem(Integer.MAX_VALUE / 2);//默认在中间，使用户看不到边界
                        //开始轮播效果
                        Log.i(TAG, "sendEmptyMessageDelayed: ");
                        handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);
                    } else {
                        viewPager.setVisibility(View.GONE);
                        imageView.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    //解析布局
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.home_classify, null);
                    //获取控件
                    GridView gvClassify = (GridView) convertView.findViewById(R.id.home_classify_list);

                    if (null != classify) {
                        gvClassify.setVisibility(View.VISIBLE);
                        //适配器
                        MyClassifyAdapter adapter1 = new MyClassifyAdapter(classify, getActivity());
                        //添加数据
                        gvClassify.setAdapter(adapter1);
                    } else {
                        gvClassify.setVisibility(View.GONE);
                    }
                    break;
                case 2:
                    //解析布局
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.home_hot, null);
                    //获取控件
                    ListView lvHot = (ListView) convertView.findViewById(R.id.home_hot_list);
                    if (null != hot) {
                        lvHot.setVisibility(View.VISIBLE);
                        //适配器
                        MyHotAdapter adapter2 = new MyHotAdapter(hot, getActivity());
                        //添加数据
                        lvHot.setAdapter(adapter2);
                    } else {
                        lvHot.setVisibility(View.GONE);
                    }
                    break;
                case 3:
                    //解析布局
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.home_chosen, null);
                    //获取控件
                    ListView lvChosen = (ListView) convertView.findViewById(R.id.home_chosen_list);
                    if (null != chosen) {
                        lvChosen.setVisibility(View.VISIBLE);
                        //适配器
                        MyChosenAdapter adapter3 = new MyChosenAdapter(chosen, getActivity());
                        //添加数据
                        lvChosen.setAdapter(adapter3);
                    } else {
                        lvChosen.setVisibility(View.GONE);
                    }
                    break;
            }
//            LinearLayout.LayoutParams pa=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,1800);
//            convertView.setLayoutParams(pa);
            return convertView;
        }

        class MyHandler {
            public ImageView iv;
            public ViewPager viewPager;
            public LinearLayout layout;
        }
    }


    class ImageHandler extends Handler {

        /**
         * 请求更新显示的View。
         */
        protected static final int MSG_UPDATE_IMAGE = 1;
        /**
         * 请求暂停轮播。
         */
        protected static final int MSG_KEEP_SILENT = 2;
        /**
         * 请求恢复轮播。
         */
        protected static final int MSG_BREAK_SILENT = 3;
        /**
         * 记录最新的页号，当用户手动滑动时需要记录新页号，否则会使轮播的页面出错。
         * 例如当前如果在第一页，本来准备播放的是第二页，而这时候用户滑动到了末页，
         * 则应该播放的是第一页，如果继续按照原来的第二页播放，则逻辑上有问题。
         */
        protected static final int MSG_PAGE_CHANGED = 4;

        //轮播间隔时间
        protected static final long MSG_DELAY = 3000;

        //使用弱引用避免Handler泄露.这里的泛型参数可以不是Activity，也可以是Fragment等
        private WeakReference<HomePageFragment> weakReference;
        private int currentItem = 0;

        protected ImageHandler(WeakReference<HomePageFragment> wk) {
            weakReference = wk;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HomePageFragment activity = weakReference.get();
            if (activity == null) {
                //Activity已经回收，无需再处理UI了
                return;
            }
            //检查消息队列并移除未发送的消息，这主要是避免在复杂环境下消息出现重复等问题。
            if (activity.handler.hasMessages(MSG_UPDATE_IMAGE)) {
                activity.handler.removeMessages(MSG_UPDATE_IMAGE);
            }
            switch (msg.what) {
                case MSG_UPDATE_IMAGE:
                    currentItem++;
                    Log.i(TAG, "handleMessage:MSG_UPDATE_IMAGE " + currentItem);
                    activity.viewPager.setCurrentItem(currentItem);
                    //准备下次播放
                    activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_KEEP_SILENT:
                    //只要不发送消息就暂停了
                    break;
                case MSG_BREAK_SILENT:
                    activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_PAGE_CHANGED:
                    //记录当前的页号，避免播放的时候页面显示不正确。
                    Log.i(TAG, "handleMessage: " + msg.arg1);
                    currentItem = msg.arg1;
                    activity.handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                default:
                    break;
            }
        }
    }

}
